let activeEffect = null; // 记录当前的函数
const depsMap = new Map(); // 保存属性和函数的依赖关系

function track(target, key) {
  if (activeEffect) {
    let deps = depsMap.get(key);
    if (!deps) {
      deps = new Set();
      depsMap.set(key, deps);
    }
    deps.add(activeEffect);
    activeEffect.deps.push(deps); // 将当前的依赖的集合添加到函数里面
  }
  console.log(depsMap);
}

function trigger(target, key) {

  /**
   * 分析：
   *  所谓派发更新，即：从表中找到key对应的函数集合，然后将函数依次执行
   */
  let deps = depsMap.get(key);
  deps.forEach((fn) => fn());
}

const data = {
  a: 1,
  b: 2,
  c: 3,
};

const state = new Proxy(data, {
  get(target, key) {
    track(target, key);
    return target[key];
  },
  set(target, key, value) {
    target[key] = value;
    trigger(target, key);
    return true;
  },
});

function effect(fn) {
  const environment = () => {
    activeEffect = environment;
    // 清理依赖
    cleanup(environment);
    fn();
    activeEffect = null;
  };
  environment.deps = []; // 用来记录该环境函数在哪些集合里面
  environment();
}
function cleanup(environment) {
  let deps = environment.deps; // 拿到当前环境函数的依赖数组
  if (deps.length) {
    deps.forEach((dep) => {
      dep.delete(environment); // 删除依赖
      if (dep.size === 0) {
        for (let [key, value] of depsMap) {
          if (value === dep) {
            depsMap.delete(key);
          }
        }
      }
    });
    deps.length = 0;
  }
}
effect(() => {
  if (state.a === 1) {
    state.b;
  } else {
    state.c;
  }
  console.log("执行了函数1");
});
effect(() => {
  // console.log(state.a);
  console.log(state.c);
  console.log("执行了函数2");
});
state.a = 2;